package com.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.annotation.RateLimit;
import com.boot.entity.Tag;
import com.boot.service.ITagService;
import com.boot.utils.R;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/tag")
public class TagController {

    @Resource
    private ITagService tagService;

    /**
     * 分页查询标签列表
     */
    @RateLimit(limit = 20, windowSec = 60)
    @GetMapping("/list")
    public R<IPage<Tag>> listTags(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {

        Page<Tag> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Tag> wrapper = new QueryWrapper<>();

        if (name != null && !name.trim().isEmpty()) {
            wrapper.like("name", name);
        }

        wrapper.orderByDesc("created_at");
        IPage<Tag> result = tagService.page(page, wrapper);
        return R.page(result);
    }

    /**
     * 新增标签
     */
    @RateLimit(limit = 10, windowSec = 60)
    @PostMapping("/add")
    public R<Void> addTag(@RequestBody Tag tag) {
        if (tag.getName() == null || tag.getName().trim().isEmpty()) {
            return R.error("标签名不能为空");
        }
        tag.setName(tag.getName().trim());

        // 检查是否已存在同名标签
        if (tagService.getOne(new QueryWrapper<Tag>().eq("name", tag.getName())) != null) {
            return R.error("标签名已存在");
        }

        boolean saved = tagService.save(tag);
        return saved ? R.success(null) : R.error("保存失败");
    }

    /**
     * 删除标签（根据 ID）
     */
    @RateLimit(limit = 10, windowSec = 60)
    @DeleteMapping("/delete/{id}")
    public R<Void> deleteTag(@PathVariable Long id) {
        Tag tag = tagService.getById(id);
        if (tag == null) {
            return R.error("标签不存在");
        }

        boolean removed = tagService.removeById(id);
        return removed ? R.success(null) : R.error("删除失败");
    }

    /**
     * 查询标签列表
     */
    @RateLimit(limit = 20, windowSec = 60)
    @GetMapping("/listAll")
    public R<List<Tag>> listTags() {
        return R.success(tagService.list());
    }
}
